<template>
  <div class="container">
    <el-row class="header">
      <el-col :span="10" align="left">
        <el-input
          clearable
          icon="el-icon-search"
          v-model="data.params.projectName"
          placeholder="项目名称"
          style="width: 220px; margin-right: 15px"
        />
        <el-button class="ordinary" @click="search()">搜索</el-button>
      </el-col>
      <el-col :span="14" align="right">
        <el-button v-limit="'XMZX:ZXGL:JDZX:EXPORT'" class="ordinary" @click="exportExcel()"
          >批量导出</el-button
        >
        <el-button v-limit="'XMZX:ZXGL:JDZX:EXAMINE'" type="primary" @click="handleAcceptance()"
          >进度审查</el-button
        >
      </el-col>
    </el-row>

    <Table
      :loading="data.isLoading"
      :tableArr="data.allTableData"
      :columns="data.columns"
      :page-size="data.params.size"
      :page-num="data.params.current"
      @selectList="getCurrentList"
      @row-click="handleRowClick"
    >
      <template #status>
        <el-table-column label="状态" width="80">
          <template #default="{ row }">
            <span v-if="row.status == 0">未提交</span>
            <span class="pending" v-if="row.status == 1">待审批</span>
            <span class="approved" v-if="row.status == 2">审批通过</span>
            <span class="rejection" v-if="row.status == 3">已驳回</span>
          </template>
        </el-table-column>
      </template>
      <template #operate="{ row }">
        <el-button
          v-limit="'XMZX:ZXGL:JDZX:REPORT'"
          size="small"
          v-if="row.status == 0 && data.userid == row.projectLeader"
          @click="handleReport(row)"
          type="primary"
          >上报</el-button
        >
        <el-button
          v-limit="'XMZX:ZXGL:JDZX:BACK'"
          size="small"
          v-if="row.status == 1 && data.userid == row.projectLeader"
          @click="handleBack(row.id)"
          type="primary"
          >撤回</el-button
        >
        <el-button
          v-limit="'XMZX:ZXGL:JDZX:DETAIL'"
          size="small"
          class="ordinary"
          @click="handleDetail(row)"
          >详情</el-button
        >
      </template>
    </Table>
    <div class="example-pagination-block">
      <el-pagination
        background
        layout="prev, pager, next ,total,sizes,jumper"
        :total="data.total"
        :page-size="data.params.size"
        v-model:current-page="data.params.current"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </div>
    <!-- 详情弹出框 -->
    <el-dialog v-model="data.editDialog" top="10vh" width="50%" title="进度详情" @close="closeEditDialog">
      <el-tabs v-model="activeName" class="demo-tabs box">
        <el-tab-pane label="进度信息" name="1">
          <Schedule v-if="data.editDialog"></Schedule>
        </el-tab-pane>
        <el-tab-pane
          label="上报信息"
          name="2"
          v-if="data.currentRow.status != 0"
        >
          <report :currentHandle='data.currentHandle' ref="reportRef" v-if="data.editDialog"></report>
        </el-tab-pane>
        <el-tab-pane
          label="审查信息"
          name="3"
          v-if="data.currentRow.status == 2 || data.currentRow.status == 3"
        >
          <Accepance :currentHandle='data.currentHandle' v-if="data.editDialog"></Accepance>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.editDialog = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 进度审查弹出框 -->
    <el-dialog v-model="data.acceptanceDialog" top="10vh" width="60%" title="进度审查">
      <Accepance v-if="data.acceptanceDialog"></Accepance>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.acceptanceDialog = false">关闭</el-button>
          <el-button type="danger" @click="handleAcceptanceSave(3)">审查驳回</el-button>
          <el-button type="primary" @click="handleAcceptanceSave(2)">审查通过</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 上报弹出框 -->
    <el-dialog v-model="data.reportDialog" top="10vh" width="60%" title="进度上报">
      <report ref="reportRef" v-if="data.reportDialog"></report>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.reportDialog = false">关闭</el-button>
          <el-button type="primary" @click="handleReportSave()">保存</el-button>
          <!-- <el-button type="success" @click="handleReportSave()">提交</el-button> -->
        </span>
      </template>
    </el-dialog>
    <!-- 导出字段选择 -->
    <Export
      :detailList="data.detailList"
      :showing="data.exportDialog"
      @close="closeExport"
      @handle-filed="handleFiled"
    ></Export>
  </div>
</template>

<script lang="ts">
import { reactive, ref } from 'vue'
import tableData from './tableHeader.json'
import Schedule from './components/schedule.vue'
import Accepance from './components/acceptance.vue'
import report from './components/report.vue'
import Export from '@/views/project/components/Export/index.vue'

import {
  getProductList,
  getExportExcel,
  acceptanceProjects,
  acceptanceSave,
  getDetail,
} from '../../api/execute'
import Table from '../../components/table2/table.vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { useStore } from 'vuex'

export default {
  components: {
    Table,
    Schedule,
    Accepance,
    report,
    Export
  },
  setup() {
    const store = useStore()
    const activeName = ref('1')
    let data = reactive({
      params: {
        projectName: '',
        current: 1,
        size: 10,
      },
      total: 0,
      isLoading: false,
      allTableData: [],
      columns: tableData.platformTableHeader,
      ids: [],
      currentList: [] as any,
      editDialog: false,
      acceptanceDialog: false,
      reportDialog: false,
      currentRow: {} as any,
      currentHandle:'',
      exportDialog: false,
      detailList: [] as any,
      userid: JSON.parse(localStorage.getItem('userInfo') as any).userId,
    })
    const search = () => {
      data.params.current = 1
      onSearch()
    }
    const onSearch = () => {
      data.isLoading = true
      getProductList(data.params).then((res) => {
        console.log(res, 'getProductList')
        if (res.data.code == 200) {
          let result = res.data.data
          result.records.map((item) => {
            item.planPeriod =
              item.planStartPeriod.slice(0, 10) + '至' + item.planEndPeriod.slice(0, 10)
          })
          data.allTableData = result.records
          data.total = result.total
          data.isLoading = false
        }
      })
    }
    onSearch()

    const getCurrentList = (currentList) => {
      console.log(currentList, 'getCurrentList')
      data.currentList = currentList
      data.ids = currentList.map((item) => {
        return item.id
      })
    }
    //改变页码
    const handleCurrentChange = (e) => {
      console.log(e, 'handleCurrentChange')
      data.params.current = e
      onSearch()
    }
    //改变页数限制
    const handleSizeChange = (e) => {
      console.log(e, 'handleSizeChange')
      data.params.size = e
      onSearch()
    }
    const handleRowClick = (row) => {
      handleDetail(row)
    }
    const handleDetail = (row) => {
      data.currentRow = row
      data.currentHandle = '详情'
      getDetail(row.id).then((res) => {
        console.log(res.data.data, '进度执行详情')
        store.state.projectCenter.progressExecuteForm = res.data.data
        // for (let key in store.state.projectCenter.progressExecuteForm) {
        //   store.state.projectCenter.progressExecuteForm[key] = res.data.data[key]
        // }
        // store.state.projectCenter.reportForm = res.data.data
        for (let key in store.state.projectCenter.reportForm) {
          store.state.projectCenter.reportForm[key] = res.data.data[key]
        }
        // store.state.projectCenter.auditForm = res.data.data
        for (let key in store.state.projectCenter.auditForm) {
          store.state.projectCenter.auditForm[key] = res.data.data[key]
        }
        data.editDialog = true
      })
    }
    const closeEditDialog = ()=>{
      activeName.value='1'
    }
    const closeExport = () => {
      data.exportDialog = false
    }
    const handleFiled = (arr) => {
      console.log(arr, 'handleFiled')
      if (arr.length > 0) {
        ElMessageBox.confirm('您确认导出查询数据吗？', '批量导出', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          getExportExcel({ ...data.params, ids: data.ids, headList: arr })
          console.log('批量导出')
          data.exportDialog = false
        })
      }
    }
    const exportExcel = () => {
      data.exportDialog = true
      data.detailList = [
        { fieldName: 'projectName', title: '项目名称' },
        { fieldName: 'contractName', title: '合同名称' },
        { fieldName: 'nodeName', title: '进度节点名称' },
        { fieldName: 'planPeriod', title: '计划周期' },
        { fieldName: 'planContent', title: '计划内容' },
        { fieldName: 'assessmentTarget', title: '考核目标' },
      ]
    }
    // const exportExcel = () => {
    //   ElMessageBox.confirm('您确认导出查询数据吗？', '批量导出', {
    //     confirmButtonText: '确认',
    //     cancelButtonText: '取消',
    //     type: 'warning',
    //   }).then(() => {
    //     getExportExcel({ ...data.params, ids: data.ids })
    //   })
    // }
    const handleAcceptance = () => {
      if (data.ids.length) {
        let flag = true
        data.currentList.forEach((item) => {
          if (item.status != 1) {
            flag = false
          }
        })
        if (!flag) {
          ElMessage({
            message: '只能审批待审批的申请',
            type: 'warning',
          })
          return
        }
        data.acceptanceDialog = true
      } else {
        ElMessage({
          message: '请至少选择一个项目',
          type: 'warning',
        })
      }
    }
    const handleReport = (row) => {
      // 清除form表单的值
      store.commit('projectCenter/emptyReportForm')
      data.reportDialog = true
      reportForm.id = row.id
      reportForm.projectId = row.projectId
      reportForm.planContent = row.planContent
      console.log(reportForm, 'reportForm')
    }
    const handleBack = (id) => {
      ElMessageBox.confirm('您确定撤回当前申请吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        callback: (action) => {
          if (action == 'confirm') {
            console.log(action)
            acceptanceProjects([
              {
                id,
                status: 0,
              },
            ]).then((res) => {
              console.log(res)
              if (res.data.code == 200) {
                ElMessage({
                  message: '操作成功',
                  type: 'success',
                })
                onSearch()
              }
            })
          }
        },
      })
    }
    //审批
    const auditForm = store.state.projectCenter.auditForm
    const handleAcceptanceSave = (index) => {
      if (!auditForm.reviewOpinion) {
        ElMessage({
          message: '请输入审查意见',
          type: 'warning',
        })
        return
      }
      // 调用接口提交
      let params = data.ids.map((id) => {
        let obj = {
          id,
          status: index,
        }
        for (let key in auditForm) {
          obj[key] = auditForm[key]
        }
        return obj
      })
      acceptanceProjects(params).then((res) => {
        console.log(res)
        if (res.data.code == 200) {
          ElMessage({
            message: '操作成功',
            type: 'success',
          })
          onSearch()
          data.acceptanceDialog = false
        }
      })
    }
    const reportRef = ref()
    const reportForm = store.state.projectCenter.reportForm
    const handleReportSave = () => {
      reportRef.value.submitForm().then(() => {
        console.log(reportForm, 'reportForm')
        // 上报
        reportForm.status = 1
        acceptanceSave(reportForm).then((res) => {
          if (res.data.code == 200) {
            data.reportDialog = false
            onSearch()
            ElMessage({
              message: '上报成功',
              type: 'success',
            })
          } else {
            ElMessage({
              message: '上报失败',
              type: 'warning',
            })
          }
        })
      })
    }
    const handleAdd = () => {
      data.editDialog = true
    }
    return {
      data,
      activeName,
      reportRef,
      handleDetail,
      handleRowClick,
      handleAdd,
      handleAcceptance,
      handleReport,
      handleBack,
      handleAcceptanceSave,
      handleReportSave,
      exportExcel,
      closeExport,
      closeEditDialog,
      handleFiled,
      search,
      getCurrentList,
      handleCurrentChange,
      handleSizeChange,
    }
  },
}
</script>

<style lang="scss" scoped>
.container {
  background-color: white;
  // padding: 0 20px 20px;
  padding: 20px;
}
.pageName {
  font-weight: 700;
}

.el-form-item {
  .el-input {
    width: 100px;
  }

  .el-select {
    width: 100px;
  }
}

/deep/.demo-tabs > .el-tabs__content {
  max-height: 500px;
  overflow-y: scroll;
  scrollbar-width: none;
  /* Firefox */
  -ms-overflow-style: none;
  /* IE 10+ */
}

/deep/.demo-tabs > .el-tabs__content::-webkit-scrollbar {
  display: none;
  /* Chrome Safari */
}
:deep(.el-dialog__body) {
  display: block;
}
</style>
